package top.hkyzf.study.leetcode.linkedlist;

import org.junit.Test;

import java.util.List;

/**
 * @author 朱峰
 * @date 2022-1-28 9:33
 */
public class 合并两个有序链表_21 {
    public ListNode mergeTwoLists1(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        if (list1.val <= list2.val) {
            list1.next = mergeTwoLists(list1.next, list2);
            return list1;
        } else {
            list2.next = mergeTwoLists(list1, list2.next);
            return list2;
        }
    }

    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        if (list1 == null) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }
        ListNode result = new ListNode();
        ListNode next = result;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                next.next = list1;
                list1 = list1.next;
            } else {
                next.next = list2;
                list2 = list2.next;
            }
            next = next.next;
        }
        if (list1 == null) {
            next.next = list2;
        }
        if (list1 != null) {
            next.next = list1;
        }
        return result.next;
    }

    @Test
    public void testMergeTwoLists () {
        ListNode h1_node2 = new ListNode(4);
        ListNode h1_node1 = new ListNode(2, h1_node2);
        ListNode head1 = new ListNode(1, h1_node1);
        ListNode h2_node2 = new ListNode(4);
        ListNode h2_node1 = new ListNode(3, h2_node2);
        ListNode head2 = new ListNode(1, h2_node1);
        ListNode node = mergeTwoLists(head1, head2);
        while (node != null) {
            System.out.println(node);
            node = node.next;
        }
    }
}
